// src/logical/user/user.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { makeSalt, encryptPassword } from '../../../utils/cryptogram'; // 引入加密函数
import { RpAccount } from '../entity/account.entity';
import { BaseService } from '../../common/services/base.service';
import { BaseResultModel } from '../../common/models/BaseResult.model';
import { RpAccountViewModel } from '../models/accountView.model';
import { Pagination } from '../../common/models/Pagination.model';
import { BaseListResultModel } from '../../common/models/BaseListResult.model';
import { TokenInfoModel } from 'src/logical/auth/models/tokenInfo.model';
import { ResetPwdModel } from 'src/logical/auth/models/resetPwd.model';
@Injectable()
export class AccountService extends BaseService {
  constructor(
    @InjectModel(RpAccount)
    private rpAccountModel: typeof RpAccount,
  ) {
    super();
  }

  findAll(): Promise<RpAccount[]> {
    return this.rpAccountModel.findAll(); // 使用userModel查全部数据
  }
  findById(id: number | string): Promise<RpAccount> {
    return this.rpAccountModel.findByPk(id);
  }
  findByAccount(account: string): Promise<RpAccount> {
    return this.rpAccountModel.findOne({ where: { account } });
  }

  /**
   * 注册
   * @param requestBody 请求体
   */
  async save(
    requestBody: RpAccountViewModel,
    tokenInfo,
  ): Promise<any | undefined> {
    const entity = new RpAccount();
    if (!requestBody.id) {
      entity.id = this.nextId();
      entity.creatorId = tokenInfo.accountId;
      entity.createDate = this.getNowDate();

      entity.passwd = '123456';
      for (const key in requestBody) {
        if (Object.prototype.hasOwnProperty.call(requestBody, key)) {
          entity[key] = requestBody[key];
        }
      }
    } else {
      const model = await this.findById(requestBody.id);

      if (model) {
        for (const key in model.get()) {
          if (Object.prototype.hasOwnProperty.call(model.get(), key)) {
            entity[key] = model.get()[key];
          }
        }
        for (const key in requestBody) {
          if (Object.prototype.hasOwnProperty.call(requestBody, key)) {
            entity[key] = requestBody[key];
          }
        }
        entity.editorId = tokenInfo.accountId;
        entity.editDate = this.getNowDate();
      } else {
        return this.saveFailedResultData('保存失败！');
      }
    }

    try {
      // 插入或更新记录
      await RpAccount.upsert(entity);
      return this.saveSuccessResultData();
    } catch (error) {
      console.error(error);
      return this.saveFailedResultData('保存失败！');
    }
  }
  /**
   * 修改密码
   */

  async updatePwd(
    tokenInfoModel: TokenInfoModel,
    inputModel: ResetPwdModel,
  ): Promise<BaseResultModel<any>> {
    const entity = await this.findById(tokenInfoModel.accountId);

    entity.editorId = tokenInfoModel.accountId;
    // TODO: 密码加密
    entity.passwd = inputModel.password;
    entity.editDate = this.getNowDate();

    // TODO: 密码过期时间

    try {
      await this.rpAccountModel.upsert(entity.get());
      return this.resultData(null, 200, '密码修改成功！');
    } catch (error) {
      console.error(error);
      return this.saveFailedResultData('密码修改失败！');
    }
  }

  /**
   * 分页查询
   */

  async queryForList(
    queryModel,
    pagination,
  ): Promise<BaseListResultModel<Array<RpAccountViewModel>>> {
    let resList: Array<RpAccountViewModel> = new Array();
    let totalCount: number = 0;
    const pag = new Pagination();
    pag.setCurrent(pagination.current);
    pag.setPagesize(pagination.pagesize);
    pag.setTotal(pagination.total);

    resList = await this.rpAccountModel.findAll({
      where: queryModel,
      offset: pag.getCurrent() - 1,
      limit: pag.getPagesize(),
      attributes: { include: ['createDate'], exclude: ['passwd'] },
      order: [['id', 'Asc']],
      raw: true,
    });

    totalCount = await this.rpAccountModel.count();
    pag.setTotal(totalCount);

    return this.querySuccessResultListData(resList, pag);
  }

  /**
   * 查询详细
   */

  async queryDetail(id): Promise<BaseResultModel<RpAccountViewModel>> {
    const rst = await (await this.findById(id)).get();

    const accountDetailModel = new RpAccountViewModel();
    for (const key in rst) {
      if (Object.prototype.hasOwnProperty.call(rst, key)) {
        accountDetailModel[key] = rst[key];
      }
    }

    return this.getSuccessResultData(accountDetailModel);
  }
}
